/**
 *
 */

package com.yuan.unit;

import android.annotation.SuppressLint;
import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.NetworkInfo.State;
import android.net.wifi.WifiManager;
import android.os.Build;
import android.provider.Settings;
import android.telephony.TelephonyManager;
import android.text.TextUtils;

import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

/**
 * 有关网络的工具
 * 
 * @author Jiongxuan Zhang
 */
public final class NetUtils {

    /**
     * 如果当前是WAP连接，则给它返回个代理
     * 
     * @param context
     * @return
     */
    public static String checkNetInfo(Context context) {
        String apn = getApnName(context);
        if (!TextUtils.isEmpty(apn)) {

            if (apn.indexOf("cmwap") != -1
                    || apn.indexOf("3gwap") != -1
                    || apn.indexOf("uniwap") != -1) {
                return "10.0.0.172";
            } else if (apn.indexOf("ctwap") != -1) {
                return "10.0.0.200";
            }
        }

        return "";
    }

    /**
     * 获取APN的名称
     * 
     * @param context
     * @return
     */
    @SuppressLint("DefaultLocale")
    public static String getApnName(Context context) {
        ConnectivityManager connMgr = (ConnectivityManager) context
                .getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo networkInfo = connMgr.getActiveNetworkInfo();
        if (networkInfo == null) {
            return "";
        }

        int net_type = networkInfo.getType();
        if (net_type == ConnectivityManager.TYPE_WIFI) {
            return "";
        }

        if (net_type == ConnectivityManager.TYPE_MOBILE) {
            String apn = networkInfo.getExtraInfo();
            if (apn != null) {
                apn = apn.toLowerCase();

                return apn;
            }
        }

        return "";
    }

    /**
     * 获取指定运营商的编号 注：46000和46002是中国移动，46001是中国联通，46003是中国电信
     * 
     * @param context
     * @return
     */
    public static String getCarrierNumber(Context context) {
        TelephonyManager telephonyManager = (TelephonyManager) context
                .getSystemService(Context.TELEPHONY_SERVICE);
        String imsi = telephonyManager.getSubscriberId();
        if (!TextUtils.isEmpty(imsi)) {
            return imsi.substring(0, 5);
        }

        return "";
    }

    /**
     * 将entity转换成String
     * 
     * @param entity
     * @param defaultCharset
     * @return
     * @throws IOException
     * @throws ParseException
     */

    /**
     * 看当前网络是否已经连接
     * 
     * @param mContext
     * @return
     */
    public static boolean isNetworkConnected(Context context) {
        ConnectivityManager connectivityManager = (ConnectivityManager) context
                .getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo activeNetInfo = connectivityManager.getActiveNetworkInfo();
        return activeNetInfo != null && activeNetInfo.isConnected();
    }

    /**
     * 看当前网络是否可用
     * 
     * @param mContext
     * @return
     */
    public static boolean isNetworkAvailable(Context context) {
        ConnectivityManager connectivityManager = (ConnectivityManager) context
                .getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo activeNetInfo = connectivityManager.getActiveNetworkInfo();
        return activeNetInfo != null && activeNetInfo.isAvailable();
    }

    /**
     * 获取当前Wifi的连接状态
     * 
     * @param c Context
     * @return 是否在线
     */
    public static boolean isWifiConnected(Context context) {
        try {
            ConnectivityManager conMan = (ConnectivityManager) context
                    .getSystemService(Context.CONNECTIVITY_SERVICE);

            NetworkInfo info = conMan.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
            if (info == null) {
                return false;
            }

            State wifi = info.getState();
            return "CONNECTED".equalsIgnoreCase(wifi.toString());
        } catch (NullPointerException e) {
            e.printStackTrace();
            return false;
        }
    }

    public static boolean setWifiEnabled(Context context, boolean isEnabled) {
        boolean isOpen = isWifiConnected(context);
        if (isOpen == !isEnabled) {
            WifiManager wifiManager = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);
            wifiManager.setWifiEnabled(isEnabled);
        }
        return isOpen;
    }

    /**
     * @param context
     * @param isEnabled
     * @return need to start system setting
     */
    public static boolean setGPRSEnabled(Context context, boolean isEnabled) {
        boolean isOpen = isGPRSEnabled(context);
        if (isOpen == !isEnabled) {
            ConnectivityManager conMgr = (ConnectivityManager) context
                    .getSystemService(Context.CONNECTIVITY_SERVICE);
            if (Build.VERSION.SDK_INT == Build.VERSION_CODES.FROYO) {
                return true;
            } else {
                Class<?> conMgrClass = null; // ConnectivityManager类
                Field iConMgrField = null; // ConnectivityManager类中的字段
                Object iConMgr = null; // IConnectivityManager类的引用
                Class<?> iConMgrClass = null; // IConnectivityManager类
                Method setMobileDataEnabledMethod = null; // setMobileDataEnabled方法

                try {
                    // 取得ConnectivityManager类
                    conMgrClass = Class.forName(conMgr.getClass().getName());
                    // 取得ConnectivityManager类中的对象mService
                    iConMgrField = conMgrClass.getDeclaredField("mService");
                    // 设置mService可访问
                    iConMgrField.setAccessible(true);
                    // 取得mService的实例化类IConnectivityManager
                    iConMgr = iConMgrField.get(conMgr);
                    // 取得IConnectivityManager类
                    iConMgrClass = Class.forName(iConMgr.getClass().getName());
                    // 取得IConnectivityManager类中的setMobileDataEnabled(boolean)方法
                    setMobileDataEnabledMethod = iConMgrClass.getDeclaredMethod(
                            "setMobileDataEnabled", Boolean.TYPE);
                    // 设置setMobileDataEnabled方法可访问
                    setMobileDataEnabledMethod.setAccessible(true);
                    // 调用setMobileDataEnabled方法
                    setMobileDataEnabledMethod.invoke(iConMgr, isEnabled);
                } catch (ClassNotFoundException e) {
                    e.printStackTrace();
                } catch (NoSuchFieldException e) {
                    e.printStackTrace();
                } catch (SecurityException e) {
                    e.printStackTrace();
                } catch (NoSuchMethodException e) {
                    e.printStackTrace();
                } catch (IllegalArgumentException e) {
                    e.printStackTrace();
                } catch (IllegalAccessException e) {
                    e.printStackTrace();
                } catch (InvocationTargetException e) {
                    e.printStackTrace();
                }
            }
        }
        return false;
    }

    // 检测GPRS是否打开
    public static boolean isGPRSEnabled(Context context) {
        ConnectivityManager conMgr = (ConnectivityManager) context
                .getSystemService(Context.CONNECTIVITY_SERVICE);
        Class<?> conMgrClass = null; // ConnectivityManager类
        Field iConMgrField = null; // ConnectivityManager类中的字段
        Object iConMgr = null; // IConnectivityManager类的引用
        Class<?> iConMgrClass = null; // IConnectivityManager类
        Method getMobileDataEnabledMethod = null; // setMobileDataEnabled方法

        try {
            // 取得ConnectivityManager类
            conMgrClass = Class.forName(conMgr.getClass().getName());
            // 取得ConnectivityManager类中的对象mService
            iConMgrField = conMgrClass.getDeclaredField("mService");
            // 设置mService可访问
            iConMgrField.setAccessible(true);
            // 取得mService的实例化类IConnectivityManager
            iConMgr = iConMgrField.get(conMgr);
            // 取得IConnectivityManager类
            iConMgrClass = Class.forName(iConMgr.getClass().getName());
            // 取得IConnectivityManager类中的getMobileDataEnabled(boolean)方法
            getMobileDataEnabledMethod = iConMgrClass.getDeclaredMethod("getMobileDataEnabled");
            // 设置getMobileDataEnabled方法可访问
            getMobileDataEnabledMethod.setAccessible(true);
            // 调用getMobileDataEnabled方法
            return (Boolean) getMobileDataEnabledMethod.invoke(iConMgr);
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (NoSuchFieldException e) {
            e.printStackTrace();
        } catch (SecurityException e) {
            e.printStackTrace();
        } catch (NoSuchMethodException e) {
            e.printStackTrace();
        } catch (IllegalArgumentException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return false;
    }

    /**
     * 获取当前MOBILE的连接状态
     * 
     * @param c Context
     * @return 是否在线
     */
    public static boolean isGPRSConnected(Context context) {
        ConnectivityManager conMan = (ConnectivityManager) context
                .getSystemService(Context.CONNECTIVITY_SERVICE);

        NetworkInfo info = conMan.getNetworkInfo(ConnectivityManager.TYPE_MOBILE);
        return info != null && info.isConnected();
    }

    /**
     * 获取当前网络的类型（Gprs?Cdma?) 值是：TelephonyManager.NETWORK_TYPE_XXX
     * 
     * @param context
     * @return
     */
    public static int getNetworkType(Context context) {
        ConnectivityManager conMan = (ConnectivityManager) context
                .getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo info = conMan.getActiveNetworkInfo();

        if (info != null && info.getType() == ConnectivityManager.TYPE_MOBILE) {
            return info.getSubtype();
        }

        return TelephonyManager.NETWORK_TYPE_UNKNOWN;
    }

    public static boolean isAirMode(Context context) {
        @SuppressWarnings("deprecation")
        String isAirMode = Settings.System.getString(context.getContentResolver(),
                Settings.System.AIRPLANE_MODE_ON);
        return isAirMode.equals("1");
    }

    /**
     * 检查JSON的可用性
     * 
     * @param strJsonText
     * @return false if 1. string is empty. 2. string starts with anything other
     *         than '{', (white space excluded)
     */
    public static boolean checkJsonValidation(final String strJsonText) {
        if (TextUtils.isEmpty(strJsonText) == true) {
            return false;
        }
        final int len = strJsonText.length();
        for (int i = 0; i < len; i++) {
            final char c = strJsonText.charAt(i);
            if (Character.isWhitespace(c) == true) {
                continue;
            } else if (c == '{' || c == '[') {
                return true;
            }
        }
        return false;
    }

}
